package umn.monopolybankservice

import grails.converters.JSON

class PlayerController {

    def show = {
        if(params.id && Player.exists(params.id)) {
            render Player.findById(params.id).getJsonString()
        }
        else {
            render Player.list() as JSON
        }
    }
    
    def save = {
        def player = new Player(params['player'])
        if (player.save()) {
            render player.getJsonString()
        }
        else {
            //handle errors
        }
    }

    def transfer= {
        def fromPlayerId = params.get('fromPlayerId')
        def toPlayerId = params.get('toPlayerId')
        def amount = params.double('amount')
        Player fromPlayer = Player.findById(fromPlayerId)
        Player toPlayer = Player.findById(toPlayerId)
        fromPlayer.setWallet(fromPlayer.getWallet()-amount)
        fromPlayer.save(flush: true)
        toPlayer.setWallet(toPlayer.getWallet() + amount)
        toPlayer.save(flush: true)
        render fromPlayer.getJsonString()
    }

    def addPlayerToGame= {
        /*
        def playerId = params.get('playerId')
        def gameId = params.get('gameId')
        Game game = Game.findById(gameId)
        Player player = Player.findById(playerId)
        player.setGame(game)
        player.save(flush: true)
        game.refresh()
        render game.getJsonString()
        */
        Game game = Game.findByName(params.gameName)
        if (game) {
            println game.name
            Player newPlayer = new Player(name: params.playerName)
            newPlayer.wallet = game.startMoney
            newPlayer.save(flush: true)
            newPlayer.game = game
            newPlayer.save(flush: true)
            println newPlayer.name
            render newPlayer.getJsonString()
        }
        else {
            render '{"error":"game not found"}'
        }
    }

    def update = {
        if(params.id && Player.exists(params.id)) {

        }
        else {

        }
    }

    def remove = {
        if(params.id && Player.exists(params.id)) {

        }
        else {

        }
    }
}
